package com.zz.common.datasource;

import com.zz.common.annotation.TunnelSource;
import com.zz.common.config.Config;
import com.zz.common.exception.TunnelException;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.ServiceLoader;


/**
 * 数据源工厂
 */
@Slf4j
public class DataSourceFactory {

    private static DataSource tunnelSource;

    static {
        String dataSourceType = Config.getInstance().getDataSourceType();
        ServiceLoader<DataSource> dataSources = ServiceLoader.load(DataSource.class);
        for (DataSource dataSource : dataSources) {
            TunnelSource annotation = dataSource.getClass().getAnnotation(TunnelSource.class);
            if (annotation.value().equals(dataSourceType)) {
                tunnelSource = dataSource;
            }
        }
        if (!Objects.isNull(tunnelSource)) {
            tunnelSource.init();
        }
    }

    public static DataSource getTunnelSource() {
        try {
            if (Objects.isNull(tunnelSource)) {
                throw new TunnelException("数据源配置错误！");
            }
            return tunnelSource;
        } catch (Exception e) {
            throw new TunnelException("数据源配置错误！");
        }
    }


}
